import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../config/app_config.dart';

class HttpUtils {
  static final HttpUtils _instance = HttpUtils._internal();
  factory HttpUtils() => _instance;
  HttpUtils._internal();

  final String baseUrl = AppConfig.apiBaseUrl;

  Future<Map<String, dynamic>> get(String path, {Map<String, String>? headers}) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl$path'),
        headers: headers,
      );
      return _handleResponse(response);
    } catch (e) {
      return {'error': e.toString()};
    }
  }

  Future<Map<String, dynamic>> post(String path, {
    Map<String, String>? headers,
    Map<String, dynamic>? body,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl$path'),
        headers: headers,
        body: json.encode(body),
      );
      return _handleResponse(response);
    } catch (e) {
      return {'error': e.toString()};
    }
  }

  Map<String, dynamic> _handleResponse(http.Response response) {
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      return {
        'error': '请求失败: ${response.statusCode}',
        'message': response.body,
      };
    }
  }
} 